import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    history:[],
    category:[],
    list:[],
    selectIndex:-1,
    showList:[],
    result:false
  },
  mutations: {
    // 添加搜索历史和搜索数据筛选
    ADD_HISTORY(state,item){
      var index = state.history.findIndex((ele)=>{
        return ele === item
      })
      if(index != -1){
        state.history.splice(index,1)
      }
      state.history.unshift(item)
      
    },
    // 搜索数据渲染
    SEARCH_LIST(state,value){
      state.showList =[]
      state.list.forEach((ele)=>{
        if(ele.title.includes(value)){
          state.showList.push(ele)
        }
      })
      state.showList = [...state.showList]
      console.log('展示数据',state.showList)
    },
    // 获取分类项
    GET_CATEGORY(state,category){
      state.category = category
    },
    GET_SHOPPING_LIST(state,list){
      // state.showList = list
      state.list = list
    },
    // 改变选中分类
    CHANGE_SELECT(state,index){
      state.selectIndex = index
      state.showList = []
      // console.log(1231213,state.category[index].title)
      state.list.forEach(ele => {
        if(state.category[index].title===ele.cid){
          state.showList.push(ele)
        }
      });
    },
    // 价格排序
    PRICE_SORT(state){
      state.result = !state.result
      state.showList.sort((a,b)=>{
        return state.result ? a.price - b.price : b.price-a.price
      })
    }
  },
  actions: {
    // 搜索历史
    ADD_HISTORY(context,item){
      context.commit('ADD_HISTORY',item)
    },
    // 搜索数据渲染
    SEARCH_LIST(context,value){
      context.commit('SEARCH_LIST',value)
    },  
    // 获取分类数据
    GET_CATEGORY(context){
      axios.get('http://localhost:8080/fenlei.json').then((res)=>{
        // console.log(res.data.result)
        context.commit('GET_CATEGORY',res.data.result)
      }).catch((error)=>{
        console.log(error)
      })
    },
    // 获取商品列表数据
    GET_SHOPPING_LIST(context){
      axios.get('http://localhost:8080/list.json').then((res)=>{
        // console.log(res.data.result)
        context.commit('GET_SHOPPING_LIST',res.data.result)
      }).catch((error)=>{
        console.log(error)
      })
    },
    // 改变选中分类
    CHANGE_SELECT(context,index){
      context.commit('CHANGE_SELECT',index)
    },
    // 价格排序
    PRICE_SORT(context){
      context.commit('PRICE_SORT')
    }
  },
  modules: {
  }
})
